﻿#include "taiji.h"
#include <QDebug>
#include <QMessageBox>
#include "interface.h"
#include <QProcess>
#include <QApplication>
#include <QFile>

QMap<QString,QString> g_FuncMap;
QString g_Des;

TaiJi::TaiJi(QObject *parent)
    : QObject(parent)
{
}

TaiJi::~TaiJi()
{
}

void TaiJi::Excute(QString content,TJ_TYPE type)
{
    if (type == TJ_SCRIPT) {
        bool bExcute = ExcuteTJ(content);
#ifdef _WIN64
#else
        if(bExcute==false){
            qDebug()<< "start x86_64:" << QApplication::applicationDirPath().split("Runtimes")[0]+"Runtimes/x86_64/TaiJi.exe";
            qDebug() << qApp->arguments();
            if(qApp->arguments().size() < 2){
                return;
            }
            QStringList args = qApp->arguments();
            args.pop_front();
            QProcess *process = new QProcess;
            process->startDetached(QApplication::applicationDirPath().split("Runtimes")[0]+"Runtimes/x86_64/TaiJi.exe",args);
            process->waitForStarted();
        }
#endif
    }
}

bool TaiJi::Translate(QString cmdstr)
{
    if (cmdstr.startsWith("#")) {
        return false;
    }
    QStringList strlist = cmdstr.trimmed().split(":");

    if(strlist.size()==1){
        strlist << "";
    }

    if (strlist.size() < 2) {
        return false;
    }

    if(g_FuncMap.contains(strlist[0])){
        //使用x86_64 Loader调用进程
        //strlist[1].toUtf8().data()
        QStringList argList;
        argList << g_FuncMap[strlist[0]] << strlist[1].toUtf8().data();
        qDebug() << argList;
        QProcess *process = new QProcess();
        qDebug() << QApplication::applicationDirPath()+"/TaiJiLoader.exe";
        process->start(QApplication::applicationDirPath()+"/TaiJiLoader.exe",argList);
        return true;
    }else{
        return false;
    }
}

bool TaiJi::ExcuteTJ(QString content)
{
    bool bExe = false;
    content.replace("\r", "");
    QStringList cmdlist = content.split("\n");
    foreach (QString var, cmdlist){
        if(Translate(var)){
            bExe = true;
        }else{
#ifdef _WIN64
#else
            qDebug() << var;
            if(QStringLiteral("帮助") == var.trimmed()){
                QStringList args;
                args << "--help" << g_Des.toUtf8();
                QProcess *process = new QProcess;
                qDebug() << "start" << args << QApplication::applicationDirPath().split("Runtimes")[0]+"Runtimes/x86_64/TaiJi.exe";
                process->startDetached(QApplication::applicationDirPath().split("Runtimes")[0]+"Runtimes/x86_64/TaiJi.exe",args);
                process->waitForStarted();
                bExe = true;
            }
#endif
        }
    }
    return bExe;
}
